package model

import (
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

// 乐享购物车
type EnjoyCart struct {
	gorm.Model
	UserId   int32 `gorm:"type:int(11);not null;comment:用户id"`
	GoodsId  int32 `gorm:"type:int(11);not null;comment:商品id"`
	Quantity int32 `gorm:"type:int(11);not null;comment:购物车商品数量"`
	SkuId    int32 `gorm:"type:int(11);not null;comment:属性id"`
}

// 添加购物车
func (e *EnjoyCart) CreateCart() error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Create(&e).Error
	})
}

// 删除购物车商品(根据条件删除)
func (e *EnjoyCart) DeleteCart(goodsId []int32, userId int) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&e).Where("goods_id in(?) and user_id = ?", goodsId, userId).Delete(&e).Error
	})
}

// 修改购物车商品数量
func (e *EnjoyCart) UpdateCartGoodsNumber(goodsId, userId, quantity int32) (*EnjoyCart, error) {
	var enjoyCart *EnjoyCart

	return e, mysql.WithMysql(func(db *gorm.DB) error {
		err := db.Model(enjoyCart).Where("goods_id = ? and user_id = ?", goodsId, userId).Update("quantity", quantity).Error
		if err != nil {
			return err
		}

		e, err = e.GetCartInfo(goodsId, userId)
		return err
	})
}

// 购物车详情
func (e *EnjoyCart) GetCartInfo(goodsId, userId int32) (*EnjoyCart, error) {
	return e, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("goods_id = ? and user_id = ?", goodsId, userId).First(&e).Error
	})
}

// 购物车列表
func (e *EnjoyCart) GetCartList(userId int32) ([]*EnjoyCart, error) {
	var cartList []*EnjoyCart
	return cartList, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("user_id = ?", userId).Find(&cartList).Error
	})
}
